<template>
    <div class="back_contain_n">
        <!-- 头部搜索 -->
        <div class="Search_Top_Part">
			<div class="search_list" >
				<div>
					<div class="input_flex">
						<el-input clearable v-model="queryForm.customer" placeholder="客户"></el-input>
					</div>
					<div class="input_flex">
						<el-select clearable v-model="queryForm.itemId" placeholder="品类">
							<el-option v-for="(item,index) in itemList" :key="index" :label="item"
									   :value="item"/>
						</el-select>
					</div>
					<div class="input_flex">
						<el-select filterable clearable v-model="queryForm.gradeValue" placeholder="规格">
							<el-option v-for="(item,index) in gradeList" :key="index" :label="item"
									   :value="item"/>
						</el-select>
					</div>
					<div class="input_flex daterange">
						<el-date-picker v-model="time"
						:picker-options="pickerOptions"
										type="daterange"
										range-separator="-"
										start-placeholder="开始日期"
										end-placeholder="结束日期">
						</el-date-picker>
					</div>
				</div>
			</div>
            <div class="search_bt">
                <span class="zll-search" @click="getList">搜索</span>
                <span class="zll-search-reset" @click="searchReset()">重置</span>
            </div>
        </div>
		<div class="Search_Top_Input">
			<div class="addNew">
				<span @click="devolve" v-if="hasRole('plan:produce:schedule')">立即排产</span>
			</div>
		</div>
        <!-- table -->
		<sys-table class="m_table"
				   ref="systable"
				   :isMultipleSelection="true"
				   :tableData="tableData"
				   :tableLoading="tableLoading"
				   :tableHeader="tableHeader"
				   :scopeWidth="120"
				   :backCount="backCount"
				   @getBackData="getList"
				   @getSelection="getSelection"
		>
            <template slot-scope="scope" slot="operate">
                <el-button @click="edit(scope.row,'see')" type="text" size="small">查看</el-button>
            </template>
        </sys-table>
        <div class="zll-dialog">
            <popout :title="'订单 · ' + (type == 'devolve'?'排产':'排产记录')" :visible.sync="addDialog" v-if="addDialog" class="largeSize">
                <detail ref="add" v-if="type =='see'" slot="content"  :type="type" :selectItems="itemList" :editData="editData"></detail>
                <pc-detail ref="add" v-else slot="content"  :type="type" :selectItems="itemList" :editData="editData"></pc-detail>
                <template slot="bottom">
                    <p class="zll-botton Info" @click="addDialog = false">关 闭</p>
                    <p class="zll-botton" v-if="type == 'devolve'" @click="()=>{this.$refs.add.submitForm('addForm')}">立即排产</p>
                </template>
            </popout>
        </div> 
    </div>
</template>

<script>
    import Detail from '../table-one/detail'
    import pcDetail from './detail'
	import {formatDate} from "@/plugins/formatDate";
	import {getStore} from "@/plugins/localStore";
    export default {
        data(){
            return {
				tableLoading: true, //table刷新
				type: '',
				editData: {},

				queryForm: {
					gradeValue: '',
					itemId: '',
					customer: '',
					orderStatus: '3',
				},
				backCount:0,
				tableData: [],
				tableHeader: [],
				addDialog: false,

				gradeList:[],
				itemList:['单支连排','多支','伸缩','U型'],
				time: [],
				selectChoice:[],
				pickerOptions: {
					onPick: ({ minDate }) => {
						this.minDate = minDate
					},
					disabledDate: (time) => {
						if (this.minDate) {
							const oneYear = 365 * 24 * 60 * 60 * 1000
							return time.getTime() < this.minDate.getTime() ||
								time.getTime() > this.minDate.getTime() + oneYear
						}
						return false
					}
				}
            }
        },
        methods: {
			getSelection(val) {//table多选
				this.selectChoice = val;
			},

			devolve(){//需求下放
				let self = this;
				if(self.selectChoice.length == 0 ){
					self.$notify({ title: '提示', message: "至少请勾选1个订单", type: 'warning' });
					return;
				}
				let gradeValue = self.selectChoice[0].gradeValue;
				for(let data of self.selectChoice){
					if(data.gradeValue!= gradeValue){
						self.$notify({ title: '提示', message: "下发需求的订单规格必须一致", type: 'warning' });
						return;
					}
					if(data.orderStatus != '3'){
						self.$notify({ title: '提示', message: data.orderStatusCn+"状态下的订单无法下发需求", type: 'warning' });
						return;
					}
				}
				console.log(self.selectChoice)
				self.edit(self.selectChoice,'devolve')
			},
			getSysItemList() {
				let self = this;
				self.itemList = [];
				self.$http({
					url: "/jinl/sysItem/getMgItemSelect",
					method: "post",
					data: JSON.stringify({types: ['99']}),
					dataType: 'json',
					contentType: "application/json",
				}).then(resp => {
					if (resp.success) {
						self.itemList = resp.result;
					}
				});
			},

			getOrderGrades() {
				let self = this;
				self.gradeList = [];
				self.$http({
					url: "/jinl/order/getOrderGrades",
					method: "post",
				}).then(resp => {
					if (resp.success) {
						self.gradeList = resp.result;
					}
				});
			},

			deleteRow(rowData) {
				let self = this;
				self.$confirm('是否确认删除？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$http({
						url: '/jinl/order/deleteOrders',
						method: "post",
						params: {id: rowData.id}
					}).then(resp => {
						if (resp.success) {
							self.getList();
							self.$message.success('删除成功！');
							return
						}
						self.$message.error(resp.message);
					});
				});
			},

			getList(startIndex, pageRow) {
				let self = this;
				self.tableLoading = true;
				if (this.time && this.time.length == 2) {
					//date类型
					self.queryForm.startTime = formatDate(new Date(self.time[0]), 'yyyy-MM-dd')
					self.queryForm.endTime = formatDate(new Date(self.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
				} else {
					self.queryForm.startTime = ''
					self.queryForm.endTime = ''
				}
				let pageInfo = self.$refs.systable.getPageInfo(startIndex);
				if (pageInfo.pageNum == 0||startIndex == 0) {
					self.$refs.systable.resetPage();
				}
				self.queryForm.startIndex = pageInfo.pageNum;
				self.queryForm.totalPage = pageInfo.pageSize;
				let param = Object.assign({}, self.queryForm);
				self.$http({
					url: "/jinl/order/getOrderList",
					method: "post",
					data: JSON.stringify(param),
					dataType: 'json',
					contentType: "application/json",
				}).then(resp => {
					if (resp.success) {
						let userId = getStore().id;
						self.tableLoading = false;
						for(let data of resp.result){
							if(data.createUserId != userId){
								// data.price = '*****';
								// data.totalPrice = '******';
							}
						}
						self.tableData = resp.result;
						self.tableHeader = [
							{"columnValue": "orderNum", "columnName": "订单号"},
							{"columnValue": "customer", "columnName": "客户",overFlow:true},
							{"columnValue": "itemTypeId", "columnName": "品类"},
							{"columnValue": "productName", "columnName": "产品名称",overFlow:true},
							{"columnValue": "gradeValue", "columnName": "规格", width: 150,overFlow:true},
							{"columnValue": "thNumber", "columnName": "单件万支"},
							{"columnValue": "peieceNum", "columnName": "件数"},
							{"columnValue": "totalNum", "columnName": "合计(万支)"},
							{"columnValue": "storageCount", "columnName": "库存" },
							{"columnValue": "orderStatusCn", "columnName": "状态"},

						];
						if (resp.result.length > 0) {
							self.backCount = resp.result[0].count;
						} else {
							self.backCount = 0;
						}
					}
				});

			},


			edit(val, type) {
				let self = this;
				self.addDialog = true;
				self.type = type;
				self.$nextTick(() => {
					self.itemList = JSON.parse(JSON.stringify(self.itemList));
					self.editData = JSON.parse(JSON.stringify(val));
				});
			},
			searchReset() { //重置搜索
				this.time = [];
				this.queryForm = {
					gradeValue: '',
					itemId: '',
					customer: '',
					orderStatus: '3',
				};
				this.getList();
			},

			init(val){
				this.searchReset();
			},
        },
		mounted() {
			let self = this;
			// self.getSysItemList();
			self.getOrderGrades();
			self.$eventBus.$on("updatePlanOrderList", function () {
				self.addDialog = false;
				self.getList()
			})
		},

        components: {
            Detail,pcDetail
        },
        watch: {//监听viewType切换
			viewType(val){
				this.getList(val)
            }
        }
    }
</script>

<style lang="scss" scoped>
@import "@/style/SearchTop.scss";
</style>